//
//  NewPMCAdvisoryController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/5.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import PhotosUI
/// 图文咨询
class NewPMCAdvisoryController: BaseViewController {
    
    private let doctorVm: DoctorDetailViewModel
    
    /// 从眼科检查来
    private let fromMyopia: Bool
    private let recordId: String
    
    var isRecords : Bool = false
    var patientId : String?
    var patientName : String?
    
    init(with vm: DoctorDetailViewModel, recordId: String = "", fromMyopia: Bool = false) {
        doctorVm = vm
        self.fromMyopia = fromMyopia
        self.recordId = recordId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupNotification()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    private var payVm = PayViewModel(order: PayOrderModel())
    
    private var viewModel = PublishViewModel() {
        didSet {
            switch doctorVm.selectType {
            case .nurse:
                wechatPayBtn.isEnabled = viewModel.isNurseEnabled
                wechatPayBtn.setTitle("预约咨询", for: .normal)
            default:
                wechatPayBtn.isEnabled = viewModel.isAdvisoryEnable
                if patientName != nil {
                    viewModel.patientName = patientName!
                }
                if patientId != nil {
                    viewModel.patientId = patientId!
                }

            }
            
            tableView.reloadData()
        }
    }
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.showsVerticalScrollIndicator = false
            tableView.showsHorizontalScrollIndicator = false
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(PublishHeaderViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishHeaderViewCell.reuseIdentifier())
            tableView.register(PublishLabelViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishLabelViewCell.reuseIdentifier())
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_0)
            tableView.register(PublishButtonViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishButtonViewCell.reuseIdentifier())
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_1)
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_2)
            tableView.register(PublishImageViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishImageViewCell.reuseIdentifier())
            tableView.register(NewSectionHeaderView.nibForCell(),
                               forHeaderFooterViewReuseIdentifier: NewSectionHeaderView.reuseIdentifier())
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(endEditing))
            tap.cancelsTouchesInView = false
            tableView.addGestureRecognizer(tap)
        }
    }
    @IBOutlet weak var medicalInsurancePayBtn: UIButton! {
        didSet {
            medicalInsurancePayBtn.setTitle("医保支付", for: .normal)
            medicalInsurancePayBtn.setTitleColor(.white, for: .normal)
            medicalInsurancePayBtn.backgroundColor = .mainColor
            medicalInsurancePayBtn.titleLabel?.font = .regular_12
            medicalInsurancePayBtn.layer.cornerRadius = 15
            medicalInsurancePayBtn.layer.masksToBounds = true
        }
    }
    @IBOutlet private weak var wechatPayBtn: UIButton! {
        didSet {
            wechatPayBtn.setTitle("支付", for: .normal)
            wechatPayBtn.titleLabel?.font = .regular(16)
            wechatPayBtn.isEnabled = false
            wechatPayBtn.setBackgroundImage(UIImage(color: .mainColor), for: .normal)
            wechatPayBtn.setBackgroundImage(UIImage(color: .mainColorLight), for: .highlighted)
            wechatPayBtn.setBackgroundImage(UIImage(color: .mainColorGray), for: .disabled)
        }
    }
    @IBOutlet weak var tips: UILabel! {
        didSet {
            tips.font = .regular_12
            tips.textColor = .init(hex: "#666666")
        }
    }
    
    private var isAgree: Bool = false
    @IBAction func medicalInsurancePay(_ sender: Any) {
        submit(type: .medicalInsurancePay)
    }
    @IBAction func wechatPay(_ sender: Any) {
        submit(type: .wechatPay)
    }
}

// MARK: - Action
extension NewPMCAdvisoryController {
    @IBAction private func viewAgreementAction(_ sender: UIButton) {
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
        agreementView.show(type: .agreementLetter)
    }
    
    @IBAction private func agreeAction(_ sender: UIButton) {
        sender.isSelected.toggle()
        isAgree = sender.isSelected
    }
    
    @objc private func endEditing() {
        tableView.endEditing(true)
    }
    
    private func pushPayResultVc() {
        let payResultVc = PayResultViewController(with: viewModel, orderType: .advisory)
        removeCurrentVcWhenPush(payResultVc)
    }
    
    private func pushMyAdvisoryOrderVc() {
        let orderVc = MyInquiryController(with: 1, startIndex: 1)
        removeCurrentVcWhenPush(orderVc)
    }
}

extension NewPMCAdvisoryController {
    private func setupUI() {
        switch doctorVm.selectType {
        case .nurse:
            title = "护理预约咨询"
        default:
            title = "图文咨询"
        }
      
        
        if self.isRecords {
            title = "图文咨询(复诊)"
        }
        
        configureData()
    }
    
    private func configureData() {
        if fromMyopia {
            HUDTool.showActivity()
            YSGMyopiaRecordViewModel.getMyopiaRecordDetail(recordId: recordId) { (model, message, code) in
                HUDTool.hideActivity()
                switch code {
                case .failure:
                    HUDTool.showError(message: message)
                case .success:
                    if let model = model {
                        var viewModel = YSGMyopiaRecordDetailViewModel(model: model)
                        viewModel.setCheckInfoArr()
                        
                        self.viewModel.desc = viewModel.getPatientDescription()
                        
                        let imgModels = viewModel.getImageModels()
                        imgModels.forEach { model in
                            self.viewModel.append(model)
                        }
                    }
                }
            }
        }
        
        viewModel.cost = doctorVm.regFee
        viewModel.doctorName = doctorVm.doctorName
        viewModel.departmentName = doctorVm.departmentName
        viewModel.doctorOffice = doctorVm.doctorOffice
    }
    
    private func setupNotification() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(wechatPaySuccess(_:)),
                                               name: NotiName.wechatPaySuccess,
                                               object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(wechatPayFailure(_:)),
                                               name: NotiName.wechatPayFailure,
                                               object: nil)
    }
}

extension NewPMCAdvisoryController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 6
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0: return 2
        case 3: return viewModel.isAllergyHistory ? 2 : 1
        default: return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0: return firstSectionCell(at: indexPath)
        case 1: return secondSectionCell(at: indexPath)
        case 2: return thirdSectionCell(at: indexPath)
        case 3: return fourthSectionCell(at: indexPath)
        case 4: return fifthSectionCell(at: indexPath)
        case 5: return sixthSectionCell(at: indexPath)
        default: return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 0:
            let footer = UINib.loadViewFrom(YSGPublishRuleView.self)
            footer.configure(with: .advisory)
            return footer
        default: return nil
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 2, 4, 5:
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: NewSectionHeaderView.reuseIdentifier()) as? NewSectionHeaderView
            header?.configure(at: section)
            return header
        default:
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0: return indexPath.row == 0 ? 176 : 44
        case 1: return 44
        case 2: return 150
        case 3: return indexPath.row == 0 ? 44 : 80
        case 4: return 100
        case 5: return 250
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0: return 120
        default: return 0.001
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0: return 0.001
        case 2, 4, 5: return 36
        default: return 16
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch indexPath.section {
        case 1:
            if indexPath.row == 0 {
                
                if !isRecords {
                    let familyVc = FamilyViewController()
                    familyVc.delegate = self
                    navigationController?.pushViewController(familyVc, animated: true)
                }
            }
        case 2, 3, 4:
            if viewModel.patientId.isEmpty {
                HUDTool.show(message: "请先选择就诊人")
            }
        default: break
        }
    }
}

// MARK: - init cell
extension NewPMCAdvisoryController {
    private func firstSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishHeaderViewCell.reuseIdentifier(),
                                                     for: indexPath) as! PublishHeaderViewCell
            cell.delegate = self
            cell.configure(with: doctorVm)
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishLabelViewCell.reuseIdentifier(),
                                                     for: indexPath) as! PublishLabelViewCell
            
            switch doctorVm.selectType {
            case .nurse:
                cell.configure(indexPath: indexPath,vm: viewModel,isNurse: true)
            default:
                cell.configure(for: indexPath, vm: viewModel)
            }
            return cell
        }
    }
    
    private func secondSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishLabelViewCell.reuseIdentifier(),
                                                 for: indexPath) as! PublishLabelViewCell
        cell.configure(for: indexPath, vm: viewModel)
        return cell
    }
    
    private func thirdSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_0) as! PublishTextViewCell
        cell.configure(for: indexPath, vm: viewModel, delegate: self)
        return cell
    }
    
    private func fourthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishButtonViewCell.reuseIdentifier(),
                                                     for: indexPath) as! PublishButtonViewCell
            cell.delegate = self
            cell.configure(with: viewModel)
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_1,
                                                     for: indexPath) as! PublishTextViewCell
            cell.configure(for: indexPath, vm: viewModel, delegate: self)
            return cell
        }
    }
    
    private func fifthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_2,
                                                 for: indexPath) as! PublishTextViewCell
        cell.configure(for: indexPath, vm: viewModel, delegate: self)
        return cell
    }
    
    private func sixthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishImageViewCell.reuseIdentifier(),
                                                 for: indexPath) as! PublishImageViewCell
        cell.configure(with: viewModel, delegate: self)
        return cell
    }
}

extension NewPMCAdvisoryController:
    FamilyViewControllerDelegate,
    PublishTextViewCellDelegate,
    PublishImageViewCellDelegate,
    PublishButtonViewCellDelegate,
    PublishHeaderViewCellDelegate {
    func familyVc(_ vc: FamilyViewController, didSelected vm: FamilyRowViewModel) {
        viewModel.patientId = "\(vm.patientId)"
        viewModel.patientName = vm.name
    }
    
    func textViewCell(_ cell: PublishTextViewCell, didEndEdit vm: PublishViewModel) {
        viewModel = vm
    }
    
    func imageCell(didClickedPickerImage cell: PublishImageViewCell) {
        Utilities.pushLoginVc(self)
        showBottomAlert()
    }
    
    func imageCell(_ cell: PublishImageViewCell, didDeleteImage vm: PublishViewModel) {
        viewModel = vm
    }
    
    func buttonViewCell(_ cell: PublishButtonViewCell, didClickedButton vm: PublishViewModel) {
        viewModel = vm
    }
    
    func headerViewCell(didIntroduceAction cell: PublishHeaderViewCell) {
        pushDoctorDetail(with: doctorVm.doctorId)
    }
    
    private func pushDoctorDetail(with doctorId: String) {
        let detailVc = DoctorDetailController(with: doctorId)
        navigationController?.pushViewController(detailVc, animated: true)
    }
}

// MARK: - UIImagePickerControllerDelegate
extension NewPMCAdvisoryController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    private func showBottomAlert() {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        
        let cancel = UIAlertAction(title:"取消", style: .cancel, handler: nil)
        let takingPictures = UIAlertAction(title:"拍照", style: .default) {
            action in
            self.goCamera()
            
        }
        let localPhoto = UIAlertAction(title:"从手机相册选择", style: .default) {
            action in
            self.goImage()
            
        }
        alert.addAction(cancel)
        alert.addAction(takingPictures)
        alert.addAction(localPhoto)
        present(alert, animated:true, completion:nil)
        
    }
    
    private func goCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            //            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            //在需要的地方present出来
            self.present(cameraPicker, animated: true, completion: nil)
        } else {
            HUDTool.show(message: "相机权限未打开!")
        }
    }
    
    private func goImage() {
        if #available(iOS 14, *) {
            var configuration: PHPickerConfiguration = PHPickerConfiguration()
            configuration.filter = .images
            configuration.selectionLimit = 9 - viewModel.numberOfItems
            let photoPicker = PHPickerViewController(configuration: configuration)
            photoPicker.delegate = self
            self.showDetailViewController(photoPicker, sender: nil)
        } else {
            let photoPicker =  UIImagePickerController()
            photoPicker.delegate = self
            //        photoPicker.allowsEditing = true
            photoPicker.sourceType = .photoLibrary
            //在需要的地方present出来
            self.present(photoPicker, animated: true, completion: nil)
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            HUDTool.showActivity()
            retrieveNewURL(image, complete: {
                HUDTool.hideActivity()
            })
        }
        self.dismiss(animated: true, completion: nil)
    }
}
// MARK: - PHPickerViewControllerDelegate
extension NewPMCAdvisoryController: PHPickerViewControllerDelegate {
    @available(iOS 14, *)
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        let group = DispatchGroup()
        HUDTool.showActivity()
        results.forEach({ result in
            group.enter()
            let model = UploadImgModel(id: UUID().uuidString, resourceId: nil, ShareThumbnailUrl: nil, shareThumbnailUrl: nil, shareUrl: nil)
            viewModel.append(model)
            tableView.reloadData()
            
            result.itemProvider.loadObject(ofClass: UIImage.self, completionHandler: { [weak self] itemProviderReading, error in
                DispatchQueue.main.async(execute: {
                    if let image = itemProviderReading as? UIImage, error == nil {
                        self?.retrieveNewURL(image, uuid: model.id, complete: {
                            group.leave()
                        })
                    } else {
                        group.leave()
                        self?.viewModel.remove(at: model)
                    }
                })
            })
        })
        picker.dismiss(animated: true, completion: nil)
        group.notify(queue: .main, execute: {
            HUDTool.hideActivity()
        })
    }
}

// MARK: - 网络请求
private extension NewPMCAdvisoryController {
    /// 获取上传图片的 presigned url
    private func retrieveNewURL(_ image: UIImage, uuid: String? = UUID().uuidString, complete: (() -> Void)?  = nil) {
        let model = UploadImgModel(id: uuid, resourceId: nil, ShareThumbnailUrl: nil, shareThumbnailUrl: nil, shareUrl: nil)
        viewModel.append(model)
        tableView.reloadData()
    
        PublishViewModel.getPresignedUrl(imageType: .medicalRecord) { (urlStr, message, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: message)
                complete?()
            case .success:
                self.uploadImageToS3(image, urlStr: urlStr, uuid: model.id, complete: complete)
            }
        }
    }
    
    /// 上传图片到 S3
    private func uploadImageToS3(_ image: UIImage, urlStr: String, uuid: String?, complete: (() -> Void)?  = nil) {
        PublishViewModel.uploadImageBy(image, presignedUrl: urlStr) { (message, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: message)
                complete?()
            case .success:
                let resourceId = urlStr.components(separatedBy: "?").first?.components(separatedBy: "/").last ?? ""
                YSGLog("resourceId = \(resourceId), imageSize = \(image.imageSize())")
                self.saveImageToDataBase(image, objectName: resourceId, size: image.imageSize(), uuid: uuid, complete: complete)
            }
        }
    }
    
    /// 保存图片到数据库
    private func saveImageToDataBase(_ image: UIImage, objectName: String, size: Double, uuid: String?, complete: (() -> Void)?  = nil) {
        PublishViewModel.saveImageToDataBase(objectName: objectName, imageType: .medicalRecord, size: size) { (model, message, code) in
            complete?()
            switch code {
            case .failure:
                HUDTool.showError(message: message)
            case .success:
                if var model = model {
                    YSGLog(model)
                    model.id = uuid
                    self.viewModel.update(model)
                    self.tableView.reloadData()
                }
            }
        }
    }
}

// MARK: 提交订单

enum NewAdvisoryGenerateOrderEnum {
    case wechatPay
    case medicalInsurancePay
}

extension NewPMCAdvisoryController {
    
    func submit(type: NewAdvisoryGenerateOrderEnum) {
        if !isAgree {
            HUDTool.show(message: "确定知情同意书及平台免责声明")
            return
        }
        if doctorVm.selectType == .nurse{
     
            uploadNurseCondition()
            return
        }
        
        if viewModel.isShowDescAlert
        {
            AlertTool.showAlert(self, message: "如果您需要在线购药，请尽量准确描述病情内容，如以往就诊和预购买药物以往的用药情况，以便医生能够更快的了解信息”，患者可点击“继续预约”或“补充描述", sureTitle: "继续预约", cancelTitle: "补充描述", type: .double, sureHandler: {[weak self] (_) in
                self?.generateOrder(type: type)
            })
            return
        }
        generateOrder(type: type)
    }
    
    /// 生成订单
    private func generateOrder(type: NewAdvisoryGenerateOrderEnum) {
        HUDTool.showActivity()
        
        PayViewModel.generateOrder(doctorId: doctorVm.doctorId,
                                   patientId: viewModel.patientId,
                                   orderAmount: doctorVm.regFee,
                                   businessType: isRecords ? "2" : "1",
                                   success: { model in
            self.uploadCondition(model, success: { payVm in
                switch type {
                case .wechatPay:
                    self.wechatSubmitOrder(payVm)
                case .medicalInsurancePay:
                    self.medicalInsuranceSubmitOrder(payVm: payVm)
                }
            })
        }) { errorMsg in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    /// 上传患者自述
    private func uploadCondition(_ model: PayOrderModel, success: @escaping (PayViewModel) -> Void) {
        let payVm = PayViewModel(order: model)
        self.payVm = payVm
        PublishViewModel.uploadPatientCondition(doctorId: doctorVm.doctorId,
                                                patientId: viewModel.patientId,
                                                condition: viewModel.desc,
                                                imgIdsStr: viewModel.imgIds.joined(separator: ","),
                                                diagnoseId: payVm.diagnoseId,
                                                allergyHistory: viewModel.allergyHistory,
                                                pastHistory: viewModel.pastHistory) { (msg, code) in
            switch code {
            case .failure:
                HUDTool.hideActivity()
                HUDTool.showError(message: msg)
            case .success:
                success(payVm)
            }
        }
    }
    
    /// 上传患者自述 护士预约
    private func uploadNurseCondition() {
        PublishViewModel.uploadNurseCondition(isAllergyHistory: viewModel.isAllergyHistory ? 1 : 0,
                                              tbUserId: doctorVm.model.tbUserId ?? "",
                                              nurseId: doctorVm.model.id ?? "",
                                              patientId: viewModel.patientId,
                                              condition: viewModel.desc,
                                              imgIdsStr: viewModel.imgIds.joined(separator: ","),
                                              allergyHistory: viewModel.allergyHistory,
                                              pastHistory: viewModel.pastHistory) { msg, code in
            switch code {
            case .failure:
                HUDTool.hideActivity()
                HUDTool.showError(message: msg)
            case .success:
                HUDTool.show(message: "预约成功")
                let vc = YSGNurseAppointmentOrderPageViewController(defaultSelectedIndex: 1)
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    private func medicalInsuranceSubmitOrder(payVm: PayViewModel) {
        guard let query = "id=\(payVm.orderId)&token=\(UserDefaults.token)".addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed),
              let url = URL(string: "alipays://platformapi/startapp?appId=2021003169675062&page=&query=\(query)") else { return }
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }else{
            YSGToast.showToast(text: "需安装支付宝APP后使用", type: .warring)
        }
    }
    
    /// 微信支付统一提交订单
    private func wechatSubmitOrder(_ payVm: PayViewModel) {
        WXApiRequestHandler.wxPaySubmitOrder(orderId: payVm.orderId,
                                             orderAmount: doctorVm.regFee,
                                             orderType: .advisory,
                                             success: { wxModel in
            HUDTool.hideActivity()
            switch wxModel.getType {
            case 1:
                self.showSelectPayStyleView(wxModel)
            case 4:
                HUDTool.show(message: "医保已全额支付")
                self.pushPayResultVc()
            default:
                break
            }
        }) { (errorMsg, code) in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
            self.pushMyAdvisoryOrderVc()
        }
    }
    
    /// 选择支付方式
    private func showSelectPayStyleView(_ model: WXPayResult) {
        let styleView = UINib.loadViewFrom(SelectPayStyleView.self)
        styleView.show()
        styleView.configure(cost: model.ownAmount, time: "30")
        styleView.handlerClosure = { [weak self] style in
            switch style {
            case .wechat:
                self?.wechatPay(model)
            }
        }
        styleView.cancelClosure = { [weak self] in
            self?.pushMyAdvisoryOrderVc()
        }
    }
    
    /// 微信支付
    private func wechatPay(_ model: WXPayResult) {
        if !WXApi.isWXAppInstalled() {
            HUDTool.show(message: "未安装微信")
            return
        }
        
        WXApiRequestHandler.generateWXPayOrder(model: model)
    }
    
    @objc private func wechatPaySuccess(_ noti: Notification) {
        HUDTool.showActivity()
        PayViewModel.queryOrderStatus(orderId: payVm.orderId) { (errorMsg) in
            HUDTool.hideActivity()
            if errorMsg != nil {
                HUDTool.show(message: errorMsg)
                self.pushMyAdvisoryOrderVc()
            } else {
                self.pushPayResultVc()
            }
        }
    }
    
    @objc private func wechatPayFailure(_ noti: Notification) {
        HUDTool.show(message: "订单支付失败")
        pushMyAdvisoryOrderVc()
    }
}
